
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using AdventureWorks.Client.Objects;
using AdventureWorks.Client.Silverlight.EmployeeServiceRef;
using Xomega.Framework;

namespace AdventureWorks.Client.Silverlight
{
    public partial class EmployeeSearch : Page
    {
        private EmployeeCriteria criteria;
        private EmployeeRowObject list;
        private bool needsRefresh = false;

        public EmployeeSearch()
        {
            InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Enabled;
            criteria = new EmployeeCriteria();
            pnlCriteria.DataContext = criteria;
            list = new EmployeeRowObject();
            gridResults.ItemsSource = list;
            PostInitialize();
        }

        partial void PostInitialize();

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (needsRefresh) btnSearch_Click(null, null);
            needsRefresh = true;
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            criteria.Validate(true);
            ErrorList valErr = criteria.GetValidationErrors();
            if (valErr.HasErrors())
            {
                MessageBox.Show(valErr.ErrorsText, "Validation Errors", MessageBoxButton.OK);
                return;
            }
            EmployeeServiceClient svcEmployee = new EmployeeServiceClient();
            svcEmployee.ReadListCompleted += delegate(object obj, ReadListCompletedEventArgs ce)
            {
                if (ce.Error != null) MessageBox.Show(ErrorList.FromException(
                    ce.Error).ErrorsText, "Service Errors", MessageBoxButton.OK);
                else list.FromDataContract(ce.Result);
            };
            Employee_ReadListInput inReadList = new Employee_ReadListInput();
            criteria.ToDataContract(inReadList);
            svcEmployee.ReadListAsync(inReadList);
            svcEmployee.CloseAsync();
        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            list.Clear();
        }
    }
}
